﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using EPiServer;
using EPiServer.ClientScript;
using EPiServer.ClientScript.Events;
using EPiServer.Core;
using EPiServer.Editor;
using EPiServer.SpecializedProperties;
using EPiServer.UI.WebControls;
using EPiServer.Web;
using EPiServer.Web.PageExtensions;
using EPiServer.Web.PropertyControls;

namespace FilteredPageReference.UserControls
{
    public class PropertyLinkCollectionFilteredPageReferenceEditControl : UserControlBase, IPropertyLinkCollectionEditControl
    {
        // Fields
        private int _currentRow;
        private string _linkEditorUrl = "/util/FilteredPageReference/HyperLinkPropertiesFilteredPageReference.aspx";
        private LinkItemCollection _originalLinkCollection;
        protected ToolButton AddLinkButton;
        protected ToolButton HiddenSubmitButton;
        protected Repeater Links;
        protected HtmlInputHidden LinkValue;

        public string FPRData { get; set; }

        public string SessionKey { get; set; }

        // Methods
        private void AddOrEditLink(string[] linkAttributes)
        {
            int index = int.Parse(linkAttributes[0]);
            string str = linkAttributes[1];
            string str2 = linkAttributes[2];
            string str3 = linkAttributes[3];
            string str4 = linkAttributes[4];
            LinkItem link = new LinkItem();
            link.Text = str4;
            if (!string.IsNullOrEmpty(str))
            {
                link.Href = str;
            }
            if (!string.IsNullOrEmpty(str2))
            {
                link.Target = str2;
            }
            if (!string.IsNullOrEmpty(str3))
            {
                link.Title = str3;
            }
            if (index < 0)
            {
                this.NewLinkCollection.Add(link);
            }
            else
            {
                this.NewLinkCollection.Remove(index);
                this.NewLinkCollection.Add(index, link);
            }
            this.DataBindLinks();
        }

        public override void DataBind()
        {
            base.DataBind();
            this.DataBindLinks();
        }

        private void DataBindLinks()
        {
            this.CurrentRow = 0;
            this.Links.DataSource = this.NewLinkCollection;
            this.Links.DataBind();
            if (this.Links.Items.Count > 0)
            {
                this.Links.Items[0].FindControl("ImageButtonUp").Visible = false;
                this.Links.Items[this.Links.Items.Count - 1].FindControl("ImageButtonDown").Visible = false;
            }
            this.AddLinkButton.DataBind();
        }

        protected void DeleteButton_Command(object sender, CommandEventArgs e)
        {
            int index = int.Parse((string)e.CommandArgument);
            this.NewLinkCollection.Remove(index);
            this.DataBindLinks();
            this.PageLeaveCheck_SetPageChanged();
        }

        protected string GetConfirmationMessage(LinkItem item)
        {
            return string.Format(base.Translate("/edit/linkcollection/confirmdelete"), item.Text);
        }

        protected string GetFileManagerUrl()
        {
            return HtmlEditor.GetFileManagerBrowserUrl(base.PageBase.CurrentPage.PageLink, base.PageBase.CurrentPage.ParentLink, (int)base.PageBase.CurrentPage["PageFolderID"]);
        }

        protected string GetOpenEditLinkEditorFunction(LinkItem linkItem)
        {
            string mappedUrl = string.Empty;
            if (!string.IsNullOrEmpty(linkItem.Href) && !PermanentLinkMapStore.TryToMapped(linkItem.Href, out mappedUrl))
            {
                mappedUrl = linkItem.Href;
            }
            return string.Format("LinkCollectionLaunchHyperlinkDialog_{6}('{0}', {1} , '{2}', '{3}', '{4}', '{5}')", new object[] { this._linkEditorUrl, this.CurrentRow, ClientScriptUtility.ToScriptSafeString(mappedUrl), linkItem.Target, ClientScriptUtility.ToScriptSafeString(linkItem.Text), ClientScriptUtility.ToScriptSafeString(linkItem.Title), this.ScriptSafeClientID });
        }

        protected string GetOpenEmptyLinkEditorFunction()
        {
            return ("LinkCollectionLaunchHyperlinkDialog_" + this.ScriptSafeClientID + "('" + this._linkEditorUrl + "', -1, null, null, null, null)");
        }

        protected void HiddenSubmitButton_ServerClick(object sender, EventArgs e)
        {
            string[] linkAttributes = this.LinkValue.Value.Split(new char[] { '|' });
            if (string.Equals(linkAttributes[0], "delete", StringComparison.OrdinalIgnoreCase))
            {
                this.NewLinkCollection.Remove(int.Parse(linkAttributes[1]));
                this.DataBindLinks();
            }
            else
            {
                this.AddOrEditLink(linkAttributes);
            }
            this.PageLeaveCheck_SetPageChanged();
        }

        protected void MoveDown_Click(object sender, CommandEventArgs e)
        {
            int index = int.Parse((string)e.CommandArgument);
            LinkItem link = this.NewLinkCollection[index];
            this.NewLinkCollection.Remove(index);
            this.NewLinkCollection.Add(index + 1, link);
            this.DataBindLinks();
            this.PageLeaveCheck_SetPageChanged();
        }

        protected void MoveUp_Click(object sender, CommandEventArgs e)
        {
            int index = int.Parse((string)e.CommandArgument);
            LinkItem link = this.NewLinkCollection[index];
            this.NewLinkCollection.Remove(index);
            this.NewLinkCollection.Add(index - 1, link);
            this.DataBindLinks();
            this.PageLeaveCheck_SetPageChanged();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.DataBindLinks();
            ThemeUtility.RegisterThemeCss(this.Page, "PropertyLinkCollection.css");
        }

        public void SetLinkEditorUrl()
        {
            _linkEditorUrl += string.Format("?fprkey={0}&fprdata={1}&id=", SessionKey, Server.UrlEncode(FPRData));
        }

        private void PageLeaveCheck_SetPageChanged()
        {
            if (ScriptManager.IsAvailable)
            {
                ScriptManager.Current.AddEventListener(this.Page, new CustomEvent(EventType.Load, "function(){EPi.PageLeaveCheck.SetPageChanged(true);}"));
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            this.Page.ClientScript.RegisterForEventValidation("ImageButtonUp");
            this.Page.ClientScript.RegisterForEventValidation("ImageButtonDown");
            this.Page.ClientScript.RegisterForEventValidation("DeleteButton");
            base.Render(writer);
        }

        // Properties
        public int CurrentRow
        {
            get
            {
                return this._currentRow;
            }
            set
            {
                this._currentRow = value;
            }
        }

        public LinkItemCollection NewLinkCollection
        {
            get
            {
                if (this.ViewState["NewLinkCollection"] == null)
                {
                    this.ViewState["NewLinkCollection"] = new LinkItemCollection();
                    ((LinkItemCollection)this.ViewState["NewLinkCollection"]).AddRange(this.OriginalLinkCollection);
                }
                return (this.ViewState["NewLinkCollection"] as LinkItemCollection);
            }
            set
            {
                this.ViewState["NewLinkCollection"] = value;
            }
        }

        public LinkItemCollection OriginalLinkCollection
        {
            get
            {
                return this._originalLinkCollection;
            }
            set
            {
                this._originalLinkCollection = value;
            }
        }

        protected string ScriptSafeClientID
        {
            get
            {
                return ClientScriptUtility.ToScriptSafeIdentifier(this.ClientID);
            }
        }
    }
}
 
